import 'package:flutter/material.dart';
import 'package:fl_chart/fl_chart.dart';
import 'dart:math' as math;
import '../models/sleep_data_model.dart';
import '../config/sleep_theme.dart';

/// 睡眠追踪卡片组件
/// 
/// 一个功能完整的睡眠数据可视化组件，支持：
/// - 自定义数据输入
/// - 主题配置
/// - 交互回调
/// - 多语言支持
/// - 响应式设计
class SleepTrackingCard extends StatefulWidget {
  /// 睡眠数据点列表
  final List<SleepDataPoint> sleepData;
  
  /// 主题配置
  final SleepTrackingTheme theme;
  
  /// 是否启用中文显示
  final bool useChinese;
  
  /// 额外卧床时间（分钟）
  final int additionalBedTimeMinutes;
  
  /// 饼图数据（可选，如果不提供则从sleepData计算）
  final Map<SleepStage, int>? pieChartData;
  
  /// 默认显示的数据索引
  final int? defaultDisplayIndex;
  
  /// 柱状图点击回调
  final void Function(SleepDataPoint dataPoint, int index)? onBarTap;
  
  /// 柱状图悬停回调
  final void Function(SleepDataPoint? dataPoint, int? index)? onBarHover;
  
  /// 是否启用调试模式
  final bool enableDebug;

  const SleepTrackingCard({
    super.key,
    required this.sleepData,
    this.theme = const SleepTrackingTheme(),
    this.useChinese = true,
    this.additionalBedTimeMinutes = 45,
    this.pieChartData,
    this.defaultDisplayIndex,
    this.onBarTap,
    this.onBarHover,
    this.enableDebug = false,
  });

  /// 从原始数据创建组件（向后兼容）
  factory SleepTrackingCard.fromRawData(
    List<List<int>> rawData, {
    SleepTrackingTheme theme = const SleepTrackingTheme(),
    // bool useChinese = true,
    int additionalBedTimeMinutes = 45,
    Map<SleepStage, int>? pieChartData,
    int? defaultDisplayIndex,
    void Function(SleepDataPoint dataPoint, int index)? onBarTap,
    bool enableDebug = false,
  }) {
    final sleepData = rawData.map((data) => SleepDataPoint.fromList(data)).toList();
    
    return SleepTrackingCard(
      sleepData: sleepData,
      theme: theme,
      // useChinese: useChinese,
      additionalBedTimeMinutes: additionalBedTimeMinutes,
      pieChartData: pieChartData,
      defaultDisplayIndex: defaultDisplayIndex,
      onBarTap: onBarTap,
      enableDebug: enableDebug,
    );
  }

  @override
  State<SleepTrackingCard> createState() => _SleepTrackingCardState();
}

class _SleepTrackingCardState extends State<SleepTrackingCard> {
  int? _hoveredBarIndex;
  int? _selectedBarIndex;
  late SleepStats _sleepStats;

  @override
  void initState() {
    super.initState();
    _calculateStats();
  }

  @override
  void didUpdateWidget(SleepTrackingCard oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (oldWidget.sleepData != widget.sleepData || 
        oldWidget.additionalBedTimeMinutes != widget.additionalBedTimeMinutes) {
      _calculateStats();
    }
  }

  /// 计算睡眠统计数据
  void _calculateStats() {
    _sleepStats = SleepStats.fromData(
      widget.sleepData,
      additionalBedTimeMinutes: widget.additionalBedTimeMinutes,
    );
  }

  /// 获取当前要显示的数据索引
  int? get _displayIndex {
    return _hoveredBarIndex ?? 
           _selectedBarIndex ?? 
           widget.defaultDisplayIndex;
  }

  /// 获取当前显示的数据点
  SleepDataPoint? get _displayDataPoint {
    if (widget.sleepData.isEmpty || _displayIndex == null || _displayIndex! >= widget.sleepData.length) {
      return null;
    }
    return widget.sleepData[_displayIndex!];
  }

  /// 处理柱状图悬停
  void _handleBarHover(int? index) {
    if (_hoveredBarIndex != index) {
      setState(() {
        _hoveredBarIndex = index;
      });
      
      if (widget.enableDebug) {
        debugPrint('Bar hover: $index');
      }
      
      final dataPoint = index != null && index < widget.sleepData.length 
          ? widget.sleepData[index] 
          : null;
      widget.onBarHover?.call(dataPoint, index);
    }
  }

  /// 处理柱状图点击
  void _handleBarTap(int index) {
    if (index < widget.sleepData.length) {
      setState(() {
        _selectedBarIndex = _selectedBarIndex == index ? null : index;
      });
      
      if (widget.enableDebug) {
        debugPrint('Bar tapped: $index');
      }
      
      widget.onBarTap?.call(widget.sleepData[index], index);
    }
  }

  @override
  Widget build(BuildContext context) {
    if (widget.sleepData.isEmpty) {
      return _buildEmptyState();
    }

    return Container(
      width: widget.theme.cardWidth,
      padding: EdgeInsets.all(widget.theme.cardPadding),
      decoration: BoxDecoration(
        gradient: LinearGradient(
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
          colors: [
            widget.theme.cardBackgroundStart,
            widget.theme.cardBackgroundEnd,
          ],
        ),
        borderRadius: BorderRadius.circular(widget.theme.cardBorderRadius),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.4),
            blurRadius: 16,
            offset: const Offset(0, 8),
          ),
          BoxShadow(
            color: Colors.black.withOpacity(0.1),
            blurRadius: 4,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          _buildBarChartSection(),
          _buildInteractionHint(),
          const SizedBox(height: 32),
          _buildPieChartSection(),
          const SizedBox(height: 32),
          _buildSummarySection(),
        ],
      ),
    );
  }

  /// 构建空状态
  Widget _buildEmptyState() {
    return Container(
      width: widget.theme.cardWidth,
      padding: EdgeInsets.all(widget.theme.cardPadding),
      decoration: BoxDecoration(
        gradient: LinearGradient(
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
          colors: [
            widget.theme.cardBackgroundStart,
            widget.theme.cardBackgroundEnd,
          ],
        ),
        borderRadius: BorderRadius.circular(widget.theme.cardBorderRadius),
      ),
      child: Center(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Icon(
              Icons.bedtime_outlined,
              size: 64,
              color: widget.theme.textSecondary,
            ),
            const SizedBox(height: 16),
            Text(
              widget.useChinese ? '暂无睡眠数据' : 'No Sleep Data',
              style: widget.theme.labelTextStyle,
            ),
          ],
        ),
      ),
    );
  }

  /// 构建柱状图区域
  Widget _buildBarChartSection() {
    return Container(
      height: 200, // 适应垂直柱状图高度
      child: Stack(
        children: [
          // 柱状图本身
          Positioned(
            bottom: 0,
            left: 0,
            right: 0,
            height: 160, // 为垂直柱状图留出空间
            child: _buildScrollableBarChart(),
          ),
          // 固定提示框在最上层
          _buildFixedTooltip(),
        ],
      ),
    );
  }

  /// 构建交互提示
  Widget _buildInteractionHint() {
    return Padding(
      padding: const EdgeInsets.only(top: 8),
      child: Text(
         '点击柱状图查看详细数据' ,
        style: widget.theme.labelTextStyle.copyWith(fontSize: 12),
      ),
    );
  }

  /// 构建环形图区域
  Widget _buildPieChartSection() {
    return Row(
      children: [
        // 左侧统计
        Expanded(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              _buildStatItem(
                SleepStage.light.getLocalizedName(widget.useChinese),
                _sleepStats.formatDuration(_getPieChartDuration(SleepStage.light)),
                widget.theme.getStageColor(SleepStage.light),
              ),
              const SizedBox(height: 20),
              _buildStatItem(
                SleepStage.deep.getLocalizedName(widget.useChinese),
                _sleepStats.formatDuration(_getPieChartDuration(SleepStage.deep)),
                widget.theme.getStageColor(SleepStage.deep),
              ),
            ],
          ),
        ),
        
        const SizedBox(width: 20),
        
        // 中间环形图
        Expanded(
          child: Container(
            height: 120,
            padding: const EdgeInsets.all(8),
            child: PieChart(
              PieChartData(
                sectionsSpace: 0, // 移除饼图段之间的间隔
                centerSpaceRadius: widget.theme.pieChartCenterRadius,
                startDegreeOffset: -90,
                sections: _buildPieChartSections(),
              ),
            ),
          ),
        ),
        
        const SizedBox(width: 20),
        
        // 右侧统计
        Expanded(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.end,
            children: [
              _buildStatItem(
                SleepStage.awake.getLocalizedName(widget.useChinese),
                _sleepStats.formatDuration(_getPieChartDuration(SleepStage.awake)),
                widget.theme.getStageColor(SleepStage.awake),
              ),
              const SizedBox(height: 20),
              _buildStatItem(
                SleepStage.rem.getLocalizedName(widget.useChinese),
                _sleepStats.formatDuration(_getPieChartDuration(SleepStage.rem)),
                widget.theme.getStageColor(SleepStage.rem),
              ),
            ],
          ),
        ),
      ],
    );
  }

  /// 构建汇总区域
  Widget _buildSummarySection() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        _buildTimeStatItem(
          _sleepStats.formattedTotalSleep,
          widget.useChinese ? '睡眠时长' : 'Sleep Time',
        ),
        _buildTimeStatItem(
          _sleepStats.formattedTotalBedTime,
          widget.useChinese ? '卧床时长' : 'Bed Time',
        ),
      ],
    );
  }

  /// 构建固定提示框
  Widget _buildFixedTooltip() {
    final dataPoint = _displayDataPoint;
    
    // 如果没有数据点，显示通用提示
    String displayText;
    String key;
    
    if (dataPoint == null) {
      displayText = widget.useChinese ? '点击柱状图查看详细数据' : 'Tap bars for details';
      key = 'default-hint';
    } else {
      final stageName = dataPoint.stage.getLocalizedName(widget.useChinese);
      final duration = dataPoint.durationMinutes;
      displayText = '$stageName - ${duration}${widget.useChinese ? "分钟" : "min"}';
      key = '${dataPoint.stage.name}-$duration';
    }
    
    return Positioned(
      top: 0,
      left: 0,
      right: 0,
      child: Center(
        child: AnimatedContainer(
          duration: const Duration(milliseconds: 200),
          padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 10),
          decoration: BoxDecoration(
            color: widget.theme.tooltipBackground,
            borderRadius: BorderRadius.circular(20),
            border: Border.all(
              color: widget.theme.borderColor,
              width: 1,
            ),
            boxShadow: [
              BoxShadow(
                color: Colors.black.withOpacity(0.3),
                blurRadius: 8,
                offset: const Offset(0, 4),
              ),
            ],
          ),
          child: AnimatedSwitcher(
            duration: const Duration(milliseconds: 200),
            child: Text(
              displayText,
              key: ValueKey(key),
              style: widget.theme.tooltipTextStyle,
            ),
          ),
        ),
      ),
    );
  }

  /// 构建可滑动柱状图
  Widget _buildScrollableBarChart() {
    return SingleChildScrollView(
      scrollDirection: Axis.horizontal,
      padding: const EdgeInsets.symmetric(horizontal: 8),
      child: Container(
        decoration: const BoxDecoration(
          // 给整个柱状图容器添加顶部圆角
          borderRadius: BorderRadius.only(
            topLeft: Radius.circular(8),
            topRight: Radius.circular(8),
          ),
        ),
        clipBehavior: Clip.hardEdge, // 裁剪子widget超出边界的部分
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.end,
          children: widget.sleepData.asMap().entries.map((entry) {
            return _buildVerticalBar(entry.key, entry.value);
          }).toList(),
        ),
      ),
    );
  }

  /// 构建垂直柱状图项
  Widget _buildVerticalBar(int index, SleepDataPoint dataPoint) {
    // 根据睡眠阶段设置固定高度
    final height = _getStageHeight(dataPoint.stage);
    // 根据持续时间设置宽度
    final width = _getBarWidth(dataPoint.durationMinutes);
    final isSelected = _selectedBarIndex == index;
    final isActive =  isSelected;
    
    // 获取light阶段高度作为基准线
    final lightHeight = _getStageHeight(SleepStage.light);
    // 确保所有柱子在基准线处的颜色完全一致
    final baseColor = const Color.fromRGBO(67, 156, 255, 0.6);
    
    return MouseRegion(
      onEnter: (_) => _handleBarHover(index),
      onExit: (_) => _handleBarHover(null),
      child: GestureDetector(
        onTap: () => _handleBarTap(index),
        child: Container(
          width: width,
          height: height,
          margin: EdgeInsets.zero, // 移除间距，让柱子紧密连接
          child: Stack(
                          children: [
                // 根据柱子高度构建不同的结构
                ..._buildBarLayers(width, height, lightHeight, baseColor, isActive, isSelected, index),
              ],
          ),
        ),
      ),
    );
  }

  /// 根据睡眠阶段获取固定高度
  double _getStageHeight(SleepStage stage) {
    switch (stage) {
      case SleepStage.deep:
        return 140.0; // 深睡眠最高
      case SleepStage.light:
        return 100.0; // 浅睡眠中高
      case SleepStage.rem:
        return 70.0;  // REM中低
      case SleepStage.awake:
        return 30.0;  // 清醒最低
    }
  }

  /// 根据持续时间获取柱子宽度
  double _getBarWidth(int durationMinutes) {
    // 每分钟对应的像素宽度，最小宽度8，最大宽度50
    return (durationMinutes * 1.2).clamp(8.0, 50.0);
  }

  /// 构建柱子渐变，以light高度为基准线
  LinearGradient _buildBarGradient(double height, double lightHeight, Color baseColor) {
    if (height <= lightHeight) {
      // 如果柱子高度不超过light基准线，整个柱子都是固定的基础颜色
      return LinearGradient(
        begin: Alignment.topCenter,
        end: Alignment.bottomCenter,
        colors: [baseColor, baseColor], // 统一的固定颜色，无渐变
      );
    } else {
      // 如果柱子高度超过light基准线，底部light高度部分保持基础颜色，顶部超出部分做渐变
      final ratio = lightHeight / height; // light基准线在柱子中的比例位置
      
      return LinearGradient(
        begin: Alignment.topCenter,
        end: Alignment.bottomCenter,
        colors: [
          Colors.white.withOpacity(0.85), // 顶部白色（超出light高度的部分）
          baseColor,                       // light高度处的基础颜色
          baseColor,                       // light高度以下保持基础颜色
        ],
        stops: [0.0, ratio, 1.0], // 在light高度处从渐变切换到固定颜色
      );
    }
  }

  /// 构建柱子的分层结构
  List<Widget> _buildBarLayers(double width, double height, double lightHeight, Color baseColor, bool isActive, bool isSelected, int index) {
    List<Widget> layers = [];
    
    // 检查是否需要凹陷效果
    final needsConcaveTop = _needsConcaveTop(index, height);
    
    if (needsConcaveTop) {
      // 获取相邻柱子的高度，计算相交高度
      final prevHeight = _getStageHeight(widget.sleepData[index - 1].stage);
      final nextHeight = _getStageHeight(widget.sleepData[index + 1].stage);
      final intersectionHeight = math.min(prevHeight, nextHeight); // 取较低的相邻柱子高度作为相交高度
      
      // 使用自定义裁剪器实现从相交高度开始的凹陷效果
      layers.add(
        ClipPath(
          clipper: ConcaveTopClipper(
            width: width, 
            height: height, 
            radius: 6.0,
            intersectionHeight: intersectionHeight,
          ),
          child: Container(
            width: width,
            height: height,
            decoration: BoxDecoration(
              color: height <= lightHeight ? baseColor : null,
              gradient: height > lightHeight 
                ? _buildBarGradient(height, lightHeight, baseColor)
                : null,
            ),
          ),
        ),
      );
    } else {
      // 使用常规圆角
      final borderRadius = _getDynamicBorderRadius(index, height);
      
      if (height <= lightHeight) {
        // 如果柱子高度不超过light基准线，只用固定颜色
        layers.add(
          Container(
            width: width,
            height: height,
            decoration: BoxDecoration(
              borderRadius: borderRadius,
              color: baseColor, // 统一的固定颜色
            ),
          ),
        );
      } else {
        // 如果柱子高度超过light基准线，分两层：底部固定颜色 + 顶部渐变
        final extraHeight = height - lightHeight; // 超出light高度的部分
        
        // 底部：固定颜色（和其他柱子完全一样）
        layers.add(
          Positioned(
            bottom: 0,
            left: 0,
            child: Container(
              width: width,
              height: lightHeight, // 底部固定为light高度
              decoration: BoxDecoration(
                borderRadius: BorderRadius.only(
                  bottomLeft: borderRadius.bottomLeft,
                  bottomRight: borderRadius.bottomRight,
                ),
                color: baseColor, // 和其他柱子完全一样的固定颜色
              ),
            ),
          ),
        );
        
        // 顶部：渐变色（超出light高度的部分）
        layers.add(
          Positioned(
            top: 0,
            left: 0,
            child: Container(
              width: width,
              height: extraHeight, // 只有超出的部分
              decoration: BoxDecoration(
                borderRadius: BorderRadius.only(
                  topLeft: borderRadius.topLeft,
                  topRight: borderRadius.topRight,
                ),
                gradient: LinearGradient(
                  begin: Alignment.topCenter,
                  end: Alignment.bottomCenter,
                  colors: [
                    Colors.white.withOpacity(0.85), // 顶部白色
                    baseColor,                       // 底部和固定颜色一致
                  ],
                ),
              ),
            ),
          ),
        );
      }
    }
    
    // 添加交互状态覆盖层
    if (isActive) {
      final interactionBorderRadius = needsConcaveTop 
        ? BorderRadius.zero 
        : _getDynamicBorderRadius(index, height);
      layers.add(
        Container(
          width: width,
          height: height,
          decoration: BoxDecoration(
            borderRadius: interactionBorderRadius,
            color: Colors.white.withOpacity(isSelected ? 0.1 : 0.05),
          ),
        ),
      );
    }
    
    return layers;
  }

  /// 检查是否需要顶部凹陷效果
  bool _needsConcaveTop(int index, double currentHeight) {
    final isFirst = index == 0;
    final isLast = index == widget.sleepData.length - 1;
    
    // 第一个或最后一个柱子不需要凹陷效果
    if (isFirst || isLast) return false;
    
    // 中间柱子：只有当比左右两边都低时才需要顶部凹陷
    final prevHeight = _getStageHeight(widget.sleepData[index - 1].stage);
    final nextHeight = _getStageHeight(widget.sleepData[index + 1].stage);
    
    return currentHeight < prevHeight && currentHeight < nextHeight;
  }

  /// 根据位置和高度关系动态获取圆角
  BorderRadius _getDynamicBorderRadius(int index, double currentHeight) {
    final isFirst = index == 0;
    final isLast = index == widget.sleepData.length - 1;
    final radius = 6.0;
    
    // 如果是第一个柱子
    if (isFirst && isLast) {
      // 只有一个柱子，四个角都圆角
      return BorderRadius.circular(radius);
    } else if (isFirst) {
      // 第一个柱子，左边圆角 + 根据右边柱子高度决定右边圆角
      final nextHeight = _getStageHeight(widget.sleepData[index + 1].stage);
      return BorderRadius.only(
        topLeft: Radius.circular(radius),
        bottomLeft: Radius.circular(radius),
        topRight: currentHeight > nextHeight ? Radius.circular(radius) : Radius.zero,
        bottomRight: Radius.zero,
      );
    } else if (isLast) {
      // 最后一个柱子，右边圆角 + 根据左边柱子高度决定左边圆角
      final prevHeight = _getStageHeight(widget.sleepData[index - 1].stage);
      return BorderRadius.only(
        topRight: Radius.circular(radius),
        bottomRight: Radius.circular(radius),
        bottomLeft: Radius.zero, // 左下角不要圆角
        topLeft: currentHeight > prevHeight ? Radius.circular(radius) : Radius.zero,
      );
    } else {
      // 中间的柱子，根据左右柱子高度决定圆角
      final prevHeight = _getStageHeight(widget.sleepData[index - 1].stage);
      final nextHeight = _getStageHeight(widget.sleepData[index + 1].stage);
      
             // 比两边都高，给顶部圆角
       if (currentHeight > prevHeight && currentHeight > nextHeight) {
         return BorderRadius.only(
           topLeft: Radius.circular(radius),
           topRight: Radius.circular(radius),
         );
       }
       // 比两边都低的情况由凹陷裁剪器处理
       else if (currentHeight < prevHeight && currentHeight < nextHeight) {
         return BorderRadius.zero; // 凹陷效果由自定义裁剪器处理
       }
      // 其他情况，根据具体高度关系设置
      else {
        return BorderRadius.only(
          topLeft: currentHeight > prevHeight ? Radius.circular(radius) : Radius.zero,
          topRight: currentHeight > nextHeight ? Radius.circular(radius) : Radius.zero,
        );
      }
    }
  }

  /// 获取边框圆角，只对第一个和最后一个柱子设置圆角
  BorderRadius _getBorderRadius(int index) {
    final isFirst = index == 0;
    final isLast = index == widget.sleepData.length - 1;
    
    if (isFirst && isLast) {
      // 只有一个柱子时，上边两个角都圆角
      return const BorderRadius.only(
        topLeft: Radius.circular(2),
        topRight: Radius.circular(2),
      );
    } else if (isFirst) {
      // 第一个柱子，左上角圆角
      return const BorderRadius.only(
        topLeft: Radius.circular(2),
      );
    } else if (isLast) {
      // 最后一个柱子，右上角圆角
      return const BorderRadius.only(
        topRight: Radius.circular(2),
      );
    } else {
      // 中间的柱子，无圆角
      return BorderRadius.zero;
    }
  }

  /// 获取动态阴影，只给首尾柱子添加阴影
  List<BoxShadow> _getBoxShadow(int index) {
    final isFirst = index == 0;
    final isLast = index == widget.sleepData.length - 1;
    
    // 只有第一个和最后一个柱子有阴影，中间的柱子没有阴影以实现融合效果
    if (isFirst || isLast) {
      return [
        BoxShadow(
          color: Colors.black.withOpacity(0.4),
          blurRadius: 8,
          offset: const Offset(0, 4),
        ),
        BoxShadow(
          color: const Color(0xFF1E3A8A).withOpacity(0.3),
          blurRadius: 16,
          offset: const Offset(0, 8),
        ),
      ];
    } else {
      return []; // 中间柱子无阴影
    }
  }

  /// 构建统计项
  Widget _buildStatItem(String label, String value, Color color) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          children: [
            Container(
              width: 14,
              height: 14,
              decoration: BoxDecoration(
                color: color,
                borderRadius: BorderRadius.circular(3),
                boxShadow: [
                  BoxShadow(
                    color: color.withOpacity(0.3),
                    blurRadius: 4,
                    offset: const Offset(0, 2),
                  ),
                ],
              ),
            ),
            const SizedBox(width: 10),
            Flexible(
              child: Text(
                label,
                style: widget.theme.statLabelStyle,
                overflow: TextOverflow.ellipsis,
              ),
            ),
          ],
        ),
        const SizedBox(height: 6),
        Text(
          value,
          style: widget.theme.statValueStyle,
        ),
      ],
    );
  }

  /// 构建时间统计项
  Widget _buildTimeStatItem(String time, String label) {
    return Column(
      children: [
        Text(time, style: widget.theme.timeTextStyle),
        const SizedBox(height: 4),
        Text(label, style: widget.theme.labelTextStyle),
      ],
    );
  }

  /// 获取饼图数据中指定阶段的持续时间
  int _getPieChartDuration(SleepStage stage) {
    return widget.pieChartData?[stage] ?? _sleepStats.getDuration(stage);
  }

  /// 构建环形图数据
  List<PieChartSectionData> _buildPieChartSections() {
    // 使用传入的饼图数据，如果没有则使用计算的统计数据
    final dataSource = widget.pieChartData ?? {
      for (final stage in SleepStage.values)
        stage: _sleepStats.getDuration(stage)
    };
    
    return SleepStage.values.where((stage) {
      return (dataSource[stage] ?? 0) > 0;
    }).map((stage) {
      return PieChartSectionData(
        color: widget.theme.getStageColor(stage),
        value: (dataSource[stage] ?? 0).toDouble(),
        radius: widget.theme.pieChartRadius,
        showTitle: false,
        borderSide: BorderSide.none, // 移除边框以避免间隔
      );
    }).toList();
  }
}

/// 自定义裁剪器，用于创建顶部凹陷效果
class ConcaveTopClipper extends CustomClipper<Path> {
  final double width;
  final double height;
  final double radius;
  final double intersectionHeight;

  ConcaveTopClipper({
    required this.width,
    required this.height,
    required this.radius,
    required this.intersectionHeight,
  });

  @override
  Path getClip(Size size) {
    final path = Path();
    
    // 计算相交位置（从容器底部算起的距离）
    final intersectionFromBottom = height - intersectionHeight;
    
    // 从左下角开始
    path.moveTo(0, height);
    
    // 左边直线到相交高度
    path.lineTo(0, intersectionFromBottom);
    
    // 从相交高度开始的凹陷曲线
    // 左上角小段直线
    path.lineTo(radius, intersectionFromBottom);
    
    // 左上角凹陷曲线（向下凹陷）
    path.quadraticBezierTo(radius, intersectionFromBottom + radius, radius * 2, intersectionFromBottom + radius);
    
    // 顶部中间凹陷的直线部分
    path.lineTo(width - radius * 2, intersectionFromBottom + radius);
    
    // 右上角凹陷曲线（向下凹陷）
    path.quadraticBezierTo(width - radius, intersectionFromBottom + radius, width - radius, intersectionFromBottom);
    
    // 右上角小段直线
    path.lineTo(width, intersectionFromBottom);
    
    // 右边直线到底部
    path.lineTo(width, height);
    
    // 底部直线回到起点
    path.lineTo(0, height);
    
    path.close();
    return path;
  }

  @override
  bool shouldReclip(CustomClipper<Path> oldClipper) {
    return oldClipper is! ConcaveTopClipper ||
        oldClipper.width != width ||
        oldClipper.height != height ||
        oldClipper.radius != radius ||
        oldClipper.intersectionHeight != intersectionHeight;
  }
}

 